package com.livestocksolutions.intent;

import java.util.Arrays;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.livestocksolutions.ChemicalHistory;
import com.livestocksolutions.LivestockSolutions;
import com.livestocksolutions.Observation;
import com.livestocksolutions.Paddock;
import com.livestocksolutions.R;
import com.livestocksolutions.ui.ListObservationArrayAdapter;
import com.livestocksolutions.ui.ListUsableItemHistoryArrayAdapter;
import com.livestocksolutions.ui.ViewLocationPaddockArrayAdapter;
import com.livestocksolutions.ui.ViewObservationArrayAdapter;
import com.livestocksolutions.ui.ViewPaddockArrayAdapter;
import com.livestocksolutions.util.StringArrayParcelable;

/* -- Version History --
 *  1.0 : 16 September 2012 - Initial version.
 */

/**
 * This class manages a Owner object
 * @author Adam Parr
 * @version 1.0
 * 
 * @.modified 28 September 2012
 */
public class PaddockActivity extends LocationActivity {
	public static final int PADDOCKVIEW 		 	= 0;
	public static final int CHEMICALVIEW 		 	= 1;
	
	/**
	 * Stores the reference to the XML layout template for each view
	 * @see #PADDOCKVIEW
	 * @see #CHEMICALVIEW
	 */
	public static final Integer[] RESOURCEID = new Integer[]{
		R.layout.item,
		R.layout.item
	};
	
	/**
	 * List of Chemicals used in this paddock.
	 */
	protected ListUsableItemHistoryArrayAdapter chemicals;
	
	public PaddockActivity() {
		super(RESOURCEID);
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.create(savedInstanceState);
        
        if(stack.size()==0){
        	setContentView(RESOURCEID[PADDOCKVIEW]);
    		if(!built){
    			// Put the ID of this Location Object
	            id = id!=-1?id:getIntent().getExtras().getLong(ITEMID,-1);
    			Paddock p = (Paddock)LivestockSolutions.getLocationByID(id);
    			// Read initial state of the Location Object and add to locationType and observationValues
    			String[] paddockType = new String[ViewPaddockArrayAdapter.SIZE];
    			paddockType[ViewLocationPaddockArrayAdapter.ID] 			= String.valueOf(p.getID());
    			paddockType[ViewLocationPaddockArrayAdapter.NAME] 			= p.getName();
    			paddockType[ViewLocationPaddockArrayAdapter.DESCRIPTION] 	= p.getDescription();
    			paddockType[ViewPaddockArrayAdapter.AREA] 			= String.valueOf(p.getArea());
    			paddockType[ViewPaddockArrayAdapter.AREATYPE] 		= String.valueOf(p.getUnits());
    			paddockType[ViewPaddockArrayAdapter.WITHHOLDDATE] 	= p.getSafeGrazingDate()!=null?String.valueOf(p.getSafeGrazingDate().getTime()):"";
    			
    			Observation[] observationList = p.getObservations();
	            String[][] observationValues = new String[observationList.length][];
	            for(int x=0; x<observationList.length; x++){
	            	String[] item = new String[ViewObservationArrayAdapter.SIZE];
	            	item[ViewObservationArrayAdapter.ID]=String.valueOf(observationList[x].getID());
	            	item[ViewObservationArrayAdapter.DATE]=String.valueOf(observationList[x].getDate().getTime());
	            	item[ViewObservationArrayAdapter.TYPE]=String.valueOf(observationList[x].getPriority());
	            	item[ViewObservationArrayAdapter.VALUE]=observationList[x].getComment();
	    			
	            	observationValues[x]=item;
	            }
	            
	            ChemicalHistory[] chemicalList = p.getChemicalsUsed();
	            Arrays.sort(chemicalList, usableItemHistoryComparator);
	            String[][] chemicalValues = new String[chemicalList.length][ListUsableItemHistoryArrayAdapter.SIZE];
        		for(int x=0; x<chemicalList.length; x++){
        			chemicalValues[x][ListUsableItemHistoryArrayAdapter.ID]=String.valueOf(chemicalList[x].getItem().getID());
        			chemicalValues[x][ListUsableItemHistoryArrayAdapter.NAME]=chemicalList[x].getItem().getName();
        			chemicalValues[x][ListUsableItemHistoryArrayAdapter.USEDATE]=chemicalList[x].getDate()!=null?String.valueOf(chemicalList[x].getDate().getTime()):"";
        			chemicalValues[x][ListUsableItemHistoryArrayAdapter.QUANTITY]=String.valueOf(chemicalList[x].getQuantity());
        			chemicalValues[x][ListUsableItemHistoryArrayAdapter.MEASUREMENT]=chemicalList[x].getMeasurement();
        		}
				
    			locationView = new ViewPaddockArrayAdapter(this, paddockType);
    	    	observations = new ListObservationArrayAdapter(this, observationValues);
    	    	chemicals = new ListUsableItemHistoryArrayAdapter(this, chemicalValues);

		    	setPage();
		    	drawObservations();
	            
				currentState.putInt(STATEID,PADDOCKVIEW);
	    		currentState.putBoolean("built",true);
    		}
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	// Show the menu for an Location Object
        getMenuInflater().inflate(R.menu.paddock_menu, menu);
        this.menu=menu;
        return true;
    }
    
    @Override
    public void onSaveInstanceState (Bundle outState) {
    	super.saveInstanceState (outState);

    	outState.putParcelable("paddockView", new StringArrayParcelable().setStrings(locationView.get()));
    	outState.putParcelable("paddockObservation", new StringArrayParcelable().setStrings(observations.get()));
    	outState.putParcelable("paddockChemicals", new StringArrayParcelable().setStrings(chemicals.get()));
    }
    
    @Override
    public void onRestoreInstanceState(Bundle inState) {
    	locationView = new ViewPaddockArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("paddockView")).getStrings()[0]);
    	observations = new ListObservationArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("paddockObservation")).getStrings());
    	chemicals 	 = new ListUsableItemHistoryArrayAdapter(this,((StringArrayParcelable)inState.getParcelable("paddockChemicals")).getStrings());

    	super.restoreInstanceState (inState);
    }
    
    @Override
    public boolean frameSelection(int frame) {
        switch (frame) {
        	case R.id.menu_chemical:
        		showView(CHEMICALVIEW,currentState);
        		break;
        	case R.id.menu_save:
        		if(locationView.isValid()){
	        		edit = false;
	        		
	        		Paddock l = id==-1?new Paddock():(Paddock)LivestockSolutions.getLocationByID(id);
	        		l.setName(locationView.get()[0][ViewLocationPaddockArrayAdapter.NAME]);
	        		l.setDescription(locationView.get()[0][ViewLocationPaddockArrayAdapter.DESCRIPTION]);
	        		l.setArea(Double.parseDouble(locationView.get()[0][ViewPaddockArrayAdapter.AREA]));
	        		l.setUnits(Integer.parseInt(locationView.get()[0][ViewPaddockArrayAdapter.AREATYPE]));
	        		id=l.getID();
	        		if(LivestockSolutions.addLocation(l)){
	        			Toast.makeText(this,getResources().getString(R.string.message_saved,getResources().getString(R.string.paddock)),Toast.LENGTH_SHORT).show();
	        		}else{
	        			Toast.makeText(this,getResources().getString(R.string.message_errorSave,getResources().getString(R.string.paddock),getResources().getString(R.string.message_unknown)),Toast.LENGTH_SHORT).show();
	        		}
	        		
	        		built=false;
	        		onPrepareOptionsMenu(menu);
	        		showView(currentState.getInt(STATEID,LOCATIONVIEW),currentState);
	        		// Pop current view
	        		stack.pop();
	        		// Pop edit change
	        		stack.pop();
	        		break;
        		}
		        //$FALL-THROUGH$
			default:
	        	return super.frameSelection(frame);
        }
        return true;
    }
    
	@Override
	public boolean constructFrame(int view) {
		switch (view) {
			case CHEMICALVIEW:
				setContentView(RESOURCEID[CHEMICALVIEW]);
				setPage();
				drawChemicals();
				break;
			default:
				return super.constructFrame(view);
		}
		return true;
	}
	
    /**
     * Set up the view to show the relevant content
     */
    @Override
	protected void setPage(){
    	LinearLayout itemView = (LinearLayout) findViewById(R.id.listView);
    	if(edit){
			((ViewPaddockArrayAdapter)locationView).setModifyPaddock();
	    }else{
	    	((ViewPaddockArrayAdapter)locationView).setViewPaddock();
	    }
    	locationView.setRoot(itemView);
    	itemView.addView(locationView.getView(0,null, itemView),0);
    }
    
	/**
     * Draw the list of Chemicals that have been used on this Paddock.<br>
     * As these contain non-editable content, nothing can be in the middle of being altered.
     * So the whole list can be re-drawn to show any changes.
     */
	private void drawChemicals() {
		setupListTitle(R.id.selectiveListTitle, R.layout.list_item_usableitemhistory);
    	((TextView)findViewById(R.id.title)).setText(getResources().getString(R.string.menu_chemical));
    	LinearLayout view = (LinearLayout) findViewById(R.id.selectiveList);
    	view.removeAllViews();
    	if(chemicals.getCount()>0){
	    	chemicals.setRoot(view);
	    	for(int x=0; x< chemicals.getCount(); x++){
	    		View v = chemicals.getView(x, null, view);
	    		v.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						Intent intent = new Intent(PaddockActivity.this, ChemicineActivity.class);
						intent.putExtra(ITEMID, Long.parseLong(chemicals.getItem(v.getId())[ListUsableItemHistoryArrayAdapter.ID]));
				    	startActivityForResult(intent, EXISTING);
					}
				});
	    		view.addView(v,x);
	    	}
    	}else{
			view.addView(inflateLayout(R.layout.item_none,view));
		}
	}
}
